import {Injectable} from '@angular/core';
import {Observable} from "rxjs/index";


@Injectable()
export class NotificationsService {
  public permission: Permission;

  constructor() {
    this.permission = this.isSupported() ? 'default' : 'denied';
  }

  public isSupported(): boolean {
    return 'Notification' in window;
  }

  requestPermission(): void {
    let self = this;
    if ('Notification' in window) {
      Notification.requestPermission(function (status) {
        return self.permission = status;
      });
    }
  }

  create(title: string, options?: Notification): Observable<any> {
    let self = this;
    return new Observable(function (obs) {
      if (!('Notification' in window)) {
        console.log('Notifications are not available in this environment');
        obs.complete();
      }
      if (self.permission !== 'granted') {
        console.log("The user hasn't granted you permission to send push notifications");
        obs.complete();
      }
      let notify = new Notification(title, options);
      notify.onshow = function (e) {

      };
      notify.onclick = function (e) {
        notify.close();
        return obs.next({notification: notify, event: e});
      };
      notify.onerror = function (e) {
        return obs.error({notification: notify, event: e});
      };
      notify.onclose = function () {
        return obs.complete();
      };
    });
  }

  generate(source: any): Observable<any> {
    let options = {body: source.body, data: source.data, icon: source.icon};
    return this.create(source.title, options);
  }
}

export declare type Permission = 'denied' | 'granted' | 'default';

export interface Notification {
  body?: string;
  icon?: string;
  tag?: string;
  data?: any;
  renotify?: boolean;
  silent?: boolean;
  sound?: string;
  noscreen ?: boolean;
  sticky?: boolean;
  dir?: 'auto' | 'ltr' | 'rtl';
  lang?: string;
  vibrate?: number[];
}
